#!/bin/bash

# 部署目录
DEPLOY_DIR="/www/wwwroot/txstdh.jvlihd.cn"
REPO_URL="git@gitee.com:jvlihd/tx_2024stdh.git"
BRANCH="master"

# 设置 Git 凭据
GIT_USERNAME="${GIT_USERNAME}"
GIT_PASSWORD="${GIT_PASSWORD}"

# 配置 Git 凭据帮助器
git config --global credential.helper store

# 写入 Git 凭据
echo "https://${GIT_USERNAME}:${GIT_PASSWORD}@gitee.com" > ~/.git-credentials

# 创建或清空部署目录
if [ -d "$DEPLOY_DIR/.git" ]; then
  echo "Directory exists, pulling the latest changes..."
  git config --global --add safe.directory /www/wwwroot/txstdh.jvlihd.cn
  cd $DEPLOY_DIR
  git checkout $BRANCH
  git pull origin $BRANCH
else
  echo "Directory does not exist or is not a git repository, cloning the repository..."
  rm -rf $DEPLOY_DIR
  mkdir -p $DEPLOY_DIR
  cd $(dirname $DEPLOY_DIR)
  git clone -b $BRANCH $REPO_URL $(basename $DEPLOY_DIR)
fi

# 设置正确的权限
chown www:www $DEPLOY_DIR -R
chmod u+w $DEPLOY_DIR/runtime -R
chmod u+w $DEPLOY_DIR/public/uploads -R

# 重启服务（假设使用的是Apache）
# systemctl restart apache2

echo "Deployment completed successfully."

# 运行 Composer 安装
cd $DEPLOY_DIR
composer install -n

echo "Composer dependencies updated."

# 删除 Git 凭据
rm -f ~/.git-credentials

# 删除部署脚本
rm -f $0
